<template>
  <div class="pay-view">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>景点预约支付</h1>
        <p>请确认订单信息并完成支付</p>
      </div>

      <div class="pay-content">
        <!-- 左侧：订单信息 -->
        <div class="order-info">
          <!-- 1. 景点基本信息 -->
          <div class="info-section">
            <h3>景点信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">景点名称：</span>
                <span class="value">{{ orderData.scenicSpotName }}</span>
              </div>
              <div class="info-item">
                <span class="label">开放时间：</span>
                <span class="value">9:00-17:00</span>
              </div>
              <div class="info-item">
                <span class="label">联系电话：</span>
                <span class="value">0591-7745234</span>
              </div>
            </div>
          </div>

          <!-- 2. 预约详细信息 -->
          <div class="info-section">
            <h3>预约详情</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">预约日期：</span>
                <span class="value">{{ orderData.visitDate }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单时间：</span>
                <span class="value">{{
                  formatDateTime(orderData.createTime)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">单价：</span>
                <span class="value">¥{{ orderData.unitPrice }}</span>
              </div>
              <div class="info-item">
                <span class="label">游客数量：</span>
                <span class="value">{{ orderData.visitorCount }}人</span>
              </div>
              <div class="info-item total">
                <span class="label">总金额：</span>
                <span class="value price">¥{{ orderData.totalAmount }}</span>
              </div>
            </div>
          </div>

          <!-- 3. 游客信息 -->
          <div class="info-section">
            <h3>游客信息</h3>

            <!-- 主预约人信息 -->
            <div class="visitor-section">
              <h4>主预约人</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">姓名：</span>
                  <span class="value">{{ orderData.mainVisitor.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">身份证号：</span>
                  <span class="value">{{ orderData.mainVisitor.idCard }}</span>
                </div>
                <div class="info-item">
                  <span class="label">手机号：</span>
                  <span class="value">{{ orderData.mainVisitor.phone }}</span>
                </div>
              </div>
            </div>

            <!-- 代预约游客信息 -->
            <div
              v-if="orderData.otherVisitors && orderData.otherVisitors.length"
              class="visitor-section"
            >
              <h4>代预约游客</h4>
              <div
                v-for="(visitor, index) in orderData.otherVisitors"
                :key="index"
                class="other-visitor"
              >
                <div class="info-grid">
                  <div class="info-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{ visitor.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">身份证号：</span>
                    <span class="value">{{ visitor.idCard }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">手机号：</span>
                    <span class="value">{{ visitor.phone }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：支付区域 -->
        <div class="payment-section">
          <div class="payment-card">
            <h3>支付方式</h3>

            <!-- 4. 支付宝支付二维码区域 -->
            <div class="payment-method">
              <div class="payment-header">
                <i class="fas fa-qrcode"></i>
                <span>支付宝支付</span>
              </div>

              <div class="qr-code-container">
                <div class="qr-code-placeholder">
                  <!-- 预留支付宝二维码区域 -->
                  <p>支付宝支付二维码将显示在这里</p>
                  <p class="hint">请使用支付宝扫码完成支付</p>
                </div>
              </div>

              <div class="payment-amount">
                <span>应付金额：</span>
                <span class="price">¥{{ orderData.totalAmount }}</span>
              </div>

              <div class="payment-actions">
                <button class="btn-primary" @click="redirectToAlipay">
                  确认支付
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

async function redirectToAlipay() {
  try {
    // 添加更详细的调试信息
    console.log("进入支付流程");
    console.log("完整订单数据:", orderData.value);
    console.log("订单ID类型:", typeof orderData.value.id);
    console.log("订单ID值:", orderData.value.id);
    console.log("请求URL:", "/api/admin/scenicOrder/update");

    // 构建请求参数
    const requestData = {
      id: orderData.value.id,
      orderStatus: 1,
    };
    
    console.log("请求参数:", requestData);
    console.log("请求参数JSON字符串:", JSON.stringify(requestData));

    // 模拟模式开关 - 当无法连接到后端时启用
    const useMockMode = false; // 设为false时使用实际API调用
    
    if (useMockMode) {
      // 模拟成功响应
      console.log("使用模拟模式，跳过实际API调用");
      setTimeout(() => {
        console.log("订单状态更新成功:", { success: true });
        alert("支付成功");
        // 成功后跳转到/site路由对应的SiteView.vue页面
        router.push({
          path: "/site",
          name: "site",
        });
      }, 500);
    } else {
      // 实际调用后端更新订单状态接口
      console.log("开始发送API请求...");
      const response = await fetch("/api/admin/scenicOrder/update", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData),
      });

      console.log("API请求完成，响应状态码:", response.status);
      console.log("响应头信息:", response.headers);
      
      if (!response.ok) {
        throw new Error(`HTTP错误! 状态码: ${response.status}`);
      }

      const result = await response.json();
      console.log("响应数据:", result);

      if (result.code === 200) {
        console.log("订单状态更新成功:", result.data);
        alert("支付成功");
        // 成功后跳转到/site路由对应的SiteView.vue页面
        router.push({
          path: "/site",
          name: "site",
        });
      } else {
        throw new Error(result.msg || '支付失败');
      }
    }
  } catch (error) {
    console.error("更新订单状态失败:", error);
    // 在控制台展示更详细的错误信息
    console.error("完整错误对象:", error);
    alert("支付失败，请稍后重试。\n详细错误请查看控制台");
  }
}

// 订单数据初始化 - 提供基本结构避免页面渲染错误
const orderData = ref({
  id: 0, // 默认值，将由路由参数中的实际订单ID覆盖
  scenicSpotName: "加载中...",
  openingHours: "",
  contactPhone: "",
  visitDate: "",
  visitTime: "",
  createTime: new Date().toLocaleString("zh-CN"),
  unitPrice: 0,
  visitorCount: 0,
  totalAmount: 0,
  mainVisitor: {
    name: "",
    idCard: "",
    phone: "",
  },
  otherVisitors: [],
});

// 格式化日期时间
const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 处理支付
const handlePayment = () => {
  console.log("开始支付流程");
  // 这里可以集成支付宝支付逻辑
  alert("支付功能待集成");
};

// 组件挂载时可以从路由参数获取订单数据
onMounted(() => {
  // 从路由参数获取订单数据
  if (route.query.order) {
    try {
      const orderJson = decodeURIComponent(route.query.order);
      const orderFromRoute = JSON.parse(orderJson);

      // 合并路由传递的订单数据
      orderData.value = {
        ...orderData.value,
        ...orderFromRoute,
        // 确保必要的字段存在
        id: orderFromRoute.id || orderData.value.id, // 优先使用路由参数中的订单ID
        scenicSpotName:
          orderFromRoute.scenicSpotName || orderData.value.scenicSpotName,
        openingHours:
          orderFromRoute.openingHours || orderData.value.openingHours,
        contactPhone:
          orderFromRoute.contactPhone || orderData.value.contactPhone,
        visitDate: orderFromRoute.visitDate || orderData.value.visitDate,
        visitTime: orderFromRoute.visitTime || orderData.value.visitTime,
        createTime: orderFromRoute.createTime || orderData.value.createTime,
        unitPrice: orderFromRoute.unitPrice || orderData.value.unitPrice,
        visitorCount:
          orderFromRoute.visitorCount || orderData.value.visitorCount,
        totalAmount: orderFromRoute.totalAmount || orderData.value.totalAmount,
        mainVisitor: orderFromRoute.mainVisitor || orderData.value.mainVisitor,
        otherVisitors:
          orderFromRoute.otherVisitors || orderData.value.otherVisitors,
      };

      console.log("从路由获取到订单数据:", orderData.value);
    } catch (error) {
      console.error("解析订单数据失败:", error);
      // 保持默认数据
    }
  }
});
</script>

<style scoped>
.pay-view {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  font-size: 2.5rem;
  color: var(--primary-color);
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.pay-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
}

.order-info {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.info-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.info-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-section h3 {
  font-size: 1.3rem;
  color: var(--primary-color);
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--primary-color);
}

.info-section h4 {
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 15px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.info-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 2px solid #eee;
  font-weight: bold;
}

.label {
  min-width: 80px;
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
  flex: 1;
}

.price {
  color: var(--primary-color);
  font-weight: bold;
  font-size: 1.2rem;
}

.visitor-section {
  margin-bottom: 20px;
}

.other-visitor {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  border-left: 3px solid var(--secondary-color);
}

.payment-section {
  position: relative;
}

.payment-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 20px;
}

.payment-card h3 {
  font-size: 1.3rem;
  color: var(--primary-color);
  margin-bottom: 20px;
  text-align: center;
}

.payment-method {
  text-align: center;
}

.payment-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 20px;
  color: #1677ff;
  font-weight: 500;
}

.payment-header i {
  font-size: 1.2rem;
}

.qr-code-container {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.qr-code-placeholder {
  min-height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.qr-code-placeholder p {
  margin: 5px 0;
}

.hint {
  font-size: 0.9rem;
  color: #999;
}

.payment-amount {
  margin: 20px 0;
  font-size: 1.1rem;
  font-weight: 500;
}

.payment-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.btn-primary {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.btn-primary:hover {
  background: var(--secondary-color);
}

.btn-secondary {
  background: #6c757d;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.btn-secondary:hover {
  background: #5a6268;
}

@media (max-width: 768px) {
  .pay-content {
    grid-template-columns: 1fr;
  }

  .payment-card {
    position: static;
  }

  .page-header h1 {
    font-size: 2rem;
  }
}
</style>
